import { useState } from "react";
import { Button } from "./ui/button";
import { Card } from "./ui/card";
import { Dialog, DialogContent, DialogTrigger, DialogTitle, DialogDescription } from "./ui/dialog";

// 类型定义
interface McpService {
  id: string;
  name: string;
  command: string;
  args?: string[];
  env?: Record<string, string>;
}

interface McpTool {
  name: string;
  description: string;
  input_schema: any;
}

interface ToolManagerProps {
  mcpServices: McpService[];
  mcpTools: McpTool[];
  onServiceCreate: (service: Partial<McpService>) => Promise<void>;
  onServiceDelete: (id: string) => Promise<void>;
}

export function ToolManager({
  mcpServices,
  mcpTools,
  onServiceCreate,
  onServiceDelete
}: ToolManagerProps) {
  const [showToolManager, setShowToolManager] = useState(false);
  const [newService, setNewService] = useState<Partial<McpService>>({});
  const [executingTool, setExecutingTool] = useState<string | null>(null);
  const [toolResult, setToolResult] = useState<{ name: string, result: any } | null>(null);

  const handleCreateService = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newService.name || !newService.command) return;

    try {
      await onServiceCreate(newService);
      setNewService({});
      setShowToolManager(false);
    } catch (error) {
      console.error('Failed to create service:', error);
    }
  };

  const handleExecuteTool = async (toolName: string) => {
    setExecutingTool(toolName);
    try {
      // 这里应该根据工具的 input_schema 来构建参数
      // 现在我们使用一个空对象作为示例
      const result = await fetch(`/api/tools/${toolName}/run`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({}),
      });

      if (!result.ok) {
        throw new Error(`Failed to execute tool: ${result.statusText}`);
      }

      const data = await result.json();
      setToolResult({ name: toolName, result: data });
    } catch (error) {
      console.error('Failed to execute tool:', error);
      setToolResult({ name: toolName, result: { error: (error as Error).message } });
    } finally {
      setExecutingTool(null);
    }
  };

  console.log("mcpServices:", mcpServices);

  return (
    <Dialog open={showToolManager} onOpenChange={setShowToolManager}>
      <DialogTrigger asChild>
        <Button variant="outline" className="bg-gray-900/80 border-gray-600 hover:bg-gray-800">
          <span className="mr-2">🔧</span>
          Tool 管理
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-4xl max-h-[80vh] px-8 bg-gray-900 border-gray-700 text-white">
        <DialogTitle>Tool 管理</DialogTitle>
        <DialogDescription>管理 MCP 服务和工具</DialogDescription>

        <div className="flex h-[60vh] gap-6">
          {/* 左侧：服务列表 */}
          <div className="flex-1">
            <h3 className="text-lg font-semibold mb-4">MCP 服务</h3>
            <div className="space-y-2 max-h-48 overflow-y-auto mb-6">
              {mcpServices.map((service) => (
                <Card key={service.id} className="p-3 bg-gray-800 border-gray-600">
                  <div className="flex justify-between items-start">
                    <div>
                      <h4 className="font-medium text-white">{service.name}</h4>
                      <p className="text-sm text-gray-400">{service.command}</p>
                    </div>
                    <Button
                      variant="destructive"
                      onClick={() => onServiceDelete(service.id)}
                      className="text-xs px-2 py-1"
                    >
                      删除
                    </Button>
                  </div>
                </Card>
              ))}
            </div>

            <h3 className="text-lg font-semibold mb-4">可用工具</h3>
            <div className="space-y-2 max-h-48 overflow-y-auto">
              {mcpTools.map((tool) => (
                <Card key={tool.name} className="p-3 bg-gray-800 border-gray-600">
                  <div className="flex justify-between items-start">
                    <div>
                      <h4 className="font-medium text-white">{tool.name}</h4>
                      <p className="text-sm text-gray-400">{tool.description}</p>
                    </div>
                    <Button
                      variant="outline"
                      onClick={() => handleExecuteTool(tool.name)}
                      disabled={executingTool === tool.name}
                      className="text-xs px-2 py-1"
                    >
                      {executingTool === tool.name ? '执行中...' : '执行'}
                    </Button>
                  </div>
                </Card>
              ))}
            </div>

            {/* 工具执行结果展示 */}
            {toolResult && (
              <div className="mt-4 p-3 bg-gray-800 border border-gray-600 rounded-lg">
                <h4 className="font-medium text-white mb-2">工具执行结果: {toolResult.name}</h4>
                <pre className="text-sm text-gray-300 bg-gray-900 p-2 rounded overflow-x-auto">
                  {JSON.stringify(toolResult.result, null, 2)}
                </pre>
                <Button
                  variant="outline"
                  onClick={() => setToolResult(null)}
                  className="mt-2 text-xs px-2 py-1"
                >
                  关闭
                </Button>
              </div>
            )}
          </div>

          {/* 右侧：创建新服务 */}
          <div className="w-80">
            <h3 className="text-lg font-semibold mb-4">创建新服务</h3>
            <form onSubmit={handleCreateService} className="space-y-4">
              <div>
                <label className="block text-sm font-medium mb-2">服务名称</label>
                <input
                  type="text"
                  value={newService.name || ''}
                  onChange={(e) => setNewService(prev => ({ ...prev, name: e.target.value }))}
                  className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white"
                  placeholder="服务名称"
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-2">命令</label>
                <input
                  type="text"
                  value={newService.command || ''}
                  onChange={(e) => setNewService(prev => ({ ...prev, command: e.target.value }))}
                  className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white"
                  placeholder="执行命令"
                />
              </div>
              <Button type="submit" className="w-full">
                创建服务
              </Button>
            </form>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

export type { McpService, McpTool };
